<?php

namespace App\Http\Controllers\App;

use App\Http\Requests\UserCreateRequest;
use App\Http\Requests\UserUpdateRequest;
use App\Models\Permission;
use App\Models\Role;
use App\Models\User;
use Auth;
use Faker\Provider\Uuid;
use Illuminate\Http\Request;

class AdminController extends BaseController
{


    public function demo()
    {
        //一。直接用户分配权限

        $user = new User();
        //授予任何用户权限
        $user->givePermissionTo('content');

        // 你也可以一次赋予多个权限
        $user->givePermissionTo('edit articles', 'delete articles');

        // 你也可以传递一个数组
        $user->givePermissionTo(['edit articles', 'delete articles']);

        //可以撤销用户权限：
        $user->revokePermissionTo('edit articles');

        //一次性撤消并添加新的权限
        $user->syncPermissions(['edit articles', 'delete articles']);

        //测试用户是否拥有权限
        $user->hasPermissionTo('content');

        //传递一个代表权限 ID 的整数
        $user->hasPermissionTo('1');
        $user->hasPermissionTo(Permission::find(1)->id);
        $user->hasPermissionTo($somePermission->id);

        //如果用户有多个权限
        $user->hasAnyPermission(['edit articles', 'publish articles', 'unpublish articles']);

        //传递整数以通过权限 ID 进行查找
        $user->hasAnyPermission(['edit articles', 1, 5]);

        //已保存的权限将在默认警卫的 Illuminate\Auth\Access\Gate 类中注册。 因此，你可以使用 Laravel 默认的 can 功能测试用户是否拥有权限
        $user->can('edit articles');


        //二。通过角色使用权限

        $user->assignRole('writer');

        // 你也可以一次分配多个角色
        $user->assignRole('writer', 'admin');

        // 或者作为一个数组
        $user->assignRole(['writer', 'admin']);

        //角色可以从用户中删除
        $user->removeRole('writer');

        // 所有当前角色将从用户中删除，并替换为给定的数组中的角色
        $user->syncRoles(['writer', 'admin']);

        //确定用户是否具有某个角色
        $user->hasRole('writer');

        //确定用户是否具有任何给定的角色列表
        $user->hasAnyRole(Role::all());

        //确定用户是否具有所有给定的角色列表
        $user->hasAllRoles(Role::all());

    }

    public function index(Request $request)
    {
        //$request->header('X-Requested-With') == 'XMLHttpRequest'
        if($request->ajax()){
            $data = User::where('user_type', '1')->paginate($request->get('limit', 30))->toArray();
            $result = [
                'code' => 0,
                'msg' => '正在请求中...',
                'count' => $data['total'],
                'data' => $data['data']
            ];
            return response()->json($result);
        }
        return view('admin.user.admin.index');
    }

    /**
     * 创建新用户表单页面
     */
    public function create()
    {
        return view('admin.user.admin.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(UserCreateRequest $request)
    {
        $data = $request->all();
        $data['user_type'] = 1;
        $data['uuid'] = Uuid::uuid();
        $data['password'] = bcrypt($data['password']);
        if (User::create($data)){
            $result = [
                'code' => 0,
                'msg' => '添加用户成功',
                'count' => '',
                'data' => ''
            ];
            return response()->json($result);
        }
        $result = [
            'code' => 1,
            'msg' => '系统错误',
            'count' => '',
            'data' => ''
        ];
        return response()->json($result);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\View\View
     */
    public function edit($id)
    {
        $user = User::findOrFail($id);
        return view('admin.user.administrators.admin.edit',compact('user'));
    }

    /**
     * 更新用户资料
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return Response
     */
    public function update(UserUpdateRequest $request)
    {
        // $request->user() 返回一个认证用户实例...

        //$user = User::findOrFail($id);
        //$data = $request->except('password');
        //if ($request->get('password')){
        //    $data['password'] = bcrypt($request->get('password'));
        //}
        //if ($user->update($data)){
        //    return response()->json(['code'=>0,'msg'=>'更新用户成功']);
        //}
        //return response()->json(['code'=>1,'msg'=>'系统错误']);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy(Request $request)
    {
        $ids = $request->get('ids');
        if (empty($ids)){
            return response()->json(['code'=>1,'msg'=>'请选择删除项']);
        }
        if (User::destroy($ids)){
            return response()->json(['code'=>0,'msg'=>'删除成功']);
        }
        return response()->json(['code'=>1,'msg'=>'删除失败']);
    }

    /**
     * 分配角色
     */
    public function role(Request $request,$id)
    {
        $user = User::findOrFail($id);
        $roles = Role::get();
        foreach ($roles as $role){
            $role->own = $user->hasRole($role->toArray()) ? true : false;
        }
        return view('admin.user.admin.role',compact('roles','user'));
    }

    /**
     * 更新分配角色
     */
    public function assignRole(Request $request,$id)
    {
        $user = User::findOrFail($id);
        $roles = $request->get('roles',[]);
        if ($user->syncRoles($roles)){
            return response()->json(['code'=>0,'msg'=>'更新用户角色成功']);
        }
        return response()->json(['code'=>1,'msg'=>'系统错误']);
    }

    /**
     * 分配权限
     */
    public function permission(Request $request,$id)
    {
        $role = Role::findOrFail($id);
        $permission = new Permission();
        $permissions = $permission->menuData();
        foreach ($permissions as $key1 => $item1){
            $permissions[$key1]['own'] = $role->hasPermissionTo($item1['id']) ? 'checked' : false ;
            if (isset($item1['_child'])){
                foreach ($item1['_child'] as $key2 => $item2){
                    $permissions[$key1]['_child'][$key2]['own'] = $role->hasPermissionTo($item2['id']) ? 'checked' : false ;
                    if (isset($item2['_child'])){
                        foreach ($item2['_child'] as $key3 => $item3){
                            $permissions[$key1]['_child'][$key2]['_child'][$key3]['own'] = $role->hasPermissionTo($item3['id']) ? 'checked' : false ;
                        }
                    }
                }
            }
        }
        return view('admin.user.admin.permission',compact('user','permissions','data'));
    }

    /**
     * 存储权限
     */
    public function assignPermission(Request $request,$id)
    {
        $user = User::findOrFail($id);
        $permission_ids = $request->get('permission_ids');
        if (empty($permission_ids)){
            $user->permissions()->detach();//清除权限
            return response()->json(['code'=>0,'msg'=>'清除用户权限成功']);
        }
        $user->syncPermissions($permission_ids);//更新权限
        return response()->json(['code'=>0,'msg'=>'更新用户权限成功']);
    }

    public function password()
    {
        return view('admin.site.user.password');
    }

    /**
     * 修改密码
     * @param Request $request
     */
    public function assignPassword(Request $request)
    {
        $id = Auth::id();
        $user = User::find($id);
        $user->password = bcrypt($request->get('password'));
        $user->save();
    }
}
